package com.stock.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.stock.annotation.Limiter;
import com.stock.cache.Cache;
import com.stock.cache.impl.RedisCache;
import com.stock.constant.Constants;
import com.stock.entity.SysUser;
import com.stock.enums.CodeEnum;
import com.stock.exception.Exceptions;
import com.stock.mapper.SysUserMapper;
import com.stock.service.UserService;
import com.stock.util.DateTimeUtil;
import com.stock.util.IdWorkers;
import com.stock.util.RedisKeyUtil;
import com.stock.vo.CaptchaVO;
import com.stock.vo.LoginDTO;
import com.stock.vo.LoginVO;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private Cache cache;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    private IdWorkers idWorkers = new IdWorkers();

    private static final int FOUR = 4;

    @Override
    public CaptchaVO captcha() {
        //生成4位数验证码
        String captcha = RandomStringUtils.randomNumeric(FOUR);

        String key = RedisKeyUtil.generateKey(Constants.captcha_prefix, idWorkers.nextStrId());
        //缓存验证码
        cache.set(key,captcha,Constants.CAPTCHA_EXPIRE_TIME);

        return CaptchaVO.builder()
                .code(captcha)
                .rkey(key)
                .build();
    }

    @Override
    public LoginVO login(LoginDTO dto) {
        if(BeanUtil.hasNullField(dto)){
            Exceptions.cast(CodeEnum.DATA_ERROR);
        }
        if(!cache.get(dto.getRkey()).equals(dto.getCode())){
            Exceptions.cast(CodeEnum.SYSTEM_VERIFY_CODE_ERROR);
        }
        SysUser user = sysUserMapper.selectOne(Wrappers.lambdaQuery(SysUser.class)
                .eq(SysUser::getUsername,dto.getUsername()));
        if(ObjectUtil.isEmpty(user)||!passwordEncoder.matches(dto.getPassword(),user.getPassword())){
            Exceptions.cast(CodeEnum.SYSTEM_PASSWORD_ERROR);
        }
        return LoginVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .nickName(user.getNickName())
                .phone(user.getPhone())
                .build();

    }
}
